<?php

namespace ApiBundle\Controller;

use AdminBundle\Services\CacheTask;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AdminBundle\Report\NewContactTask;
use AdminBundle\Report\TaskFactory;

class ReportController extends BaseController
{
    private $device;

    /**
     * client report request.
     *
     * @Route(path="/report", name="api_report")
     * @Method({"GET", "POST"})
     */
    public function indexAction(Request $request)
    {
        // 返回结果参数
        $result = [];
        // 获取JSON包
        $data_template = [
            'device' => ['imei' => '', 'free_disk' => 0],
            'wechat' => ['username' => '', 'status' => 0, 'new_member' => []],
            'task' => []
        ];
        $data = $this->apiRequest($request, $data_template);

        $device = $data['device'];
        $wechat = $data['wechat'];

        if ($wechat['status'] != 0) {
            // 微信状态异常
            return $this->apiJson(0, '', $result);
        }

        if ($this->getDevice($device['imei']) == null) {
            // 微信状态异常
            return $this->apiJson(Response::HTTP_NOT_FOUND, '终端不存在,请初始化.', $result);
        }

        // 新增成员好友
        $new_members = isset($wechat['new_member']) ? $wechat['new_member'] : [];
        $this->memberNew($wechat['username'], $new_members);

        // 任务结果
        $this->doTask($device['imei'], $wechat['username'], $data['task']);

        $message = '';
        // 成功返回
        return $this->apiJson(0, $message, $result);
    }

    private function getDevice($imei)
    {
        $em = $this->getDoctrine()->getManager();
        $this->device = $em->getRepository('AdminBundle:BaseDevice')->findOneBy(['imei' => $imei]);
        return $this->device;
    }

    /**
     * 处理汇报任务结果
     * @param $tasks
     * @param $em
     * @return mixed
     */
    private function doTask($imei, $userName, &$tasks)
    {
        // record to redis queue and delete original key
        $config = $this->getParameter('redis');
        $cacheTask = CacheTask::getInstance($config);

        foreach ($tasks as $task) {
            $task['device'] = [
                'imei' => $imei,
                'ip' => $this->ip,
                'username' => $this->username];
            $task['wechat']['username'] = $userName;

            $cacheTask->taskLog($userName, $task['id'], $task);
        }
        return count($tasks);

        // tackle obesity data of database directly .
        $queue_id = [];
        foreach ($tasks as $task) {
            $queue_id[] = $task['id'];

            if ($task['status'] != 0)
                continue;
            $taskFactory = TaskFactory::create($task['uri']);
            if ($taskFactory == null) {
                continue;
            }
            $taskFactory->setTask($task)
                ->setIp($this->ip)
                ->setUsername($this->username)
                ->setDevice($this->device)
                ->setDoctrineManager($this->getDoctrine()->getManager());

            $report = $taskFactory->report();

            unset($task);

            if ($report == null) {
                continue 1;
            }
        }
        // todo: 删除已经分配,并执行完的任务
        $this->taskClear($userName, $queue_id);
//        $em = $this->getDoctrine()->getManager();
//        $em->getRepository('AdminBundle:TaskQueueWaiting')->deleteDelivery($queue_id);
        return count($queue_id);
    }

    private function taskClear($username, $queue_id)
    {
        $config = $this->getParameter('redis');
        $cacheTask = CacheTask::getInstance($config);
        return $cacheTask->clearTaskByUserName(
            $this->getDoctrine()->getManager(),
            $username,
            $queue_id);
    }

    /**
     * 成员好友更新，新增
     * @param $webchatId
     * @param $members
     * @return int
     */
    private function memberNew($webchatId, &$members)
    {
        $count = 0;
        if (empty($members) || empty($webchatId)) {
            return $count;
        }

        $taskFactory = new NewContactTask();
        $taskFactory->setDevice($this->device)
            ->setIp($this->ip)
            ->setUsername($this->username)
            ->setDoctrineManager($this->getDoctrine()->getManager())
            ->setTask(['username' => $webchatId, 'new_member' => $members]);

        $count = $taskFactory->report();

        unset($taskFactory);
        return $count;
    }
}
